package com.universal.common.utils;

import com.google.common.collect.Lists;
import com.universal.converter.spring.Converter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

/**
 * Entity对象转VO
 *
 * @author: austin
 * @date: 2022/11/7 22:07
 */
public class ConverterUtils {

    private final static Logger logger = LoggerFactory.getLogger(ConverterUtils.class);

    public static <E, V> V toVo(E e, Class<V> clazz) {
        Object object = null;
        try {
            object = clazz.getDeclaredConstructor().newInstance();
        } catch (InstantiationException ex) {
            logger.error("对象转换异常...");
            throw new RuntimeException(ex);
        } catch (IllegalAccessException ex) {
            logger.error("对象转换异常...");
            throw new RuntimeException(ex);
        } catch (InvocationTargetException ex) {
            logger.error("对象转换异常...");
            throw new RuntimeException(ex);
        } catch (NoSuchMethodException ex) {
            logger.error("对象转换异常...");
            throw new RuntimeException(ex);
        }
        if (e == null) {
            return (V) object;
        }
        BeanUtils.copyProperties(e, object);
        return (V) object;
    }

    public static <E, V> List<V> toVo(List<E> es, Class<V> clazz) {
        List<V> targets = Lists.newArrayList();
        if (CollectionUtils.isEmpty(es)) {
            return targets;
        }
        es.stream().forEach(e -> targets.add(toVo(e, clazz)));
        return targets;
    }


    public static <E, V> List<V> toVo(List<E> es, Converter<E, V> converter) {
        List<V> targets = Lists.newArrayList();
        if (CollectionUtils.isEmpty(es)) {
            return targets;
        }
        es.stream().forEach(e -> targets.add(converter.convert(e)));
        return targets;
    }

    public static <E, V> V beanConvert(E source, Class<V> clazz) {
        Object object = null;
        try {
            object = clazz.newInstance();
        } catch (InstantiationException e1) {
            logger.error("对象转换异常：{}", source);
        } catch (IllegalAccessException e1) {
            logger.error("对象转换异常：{}", source);
        }
        if (source == null) {
            return (V) object;
        }
        BeanUtils.copyProperties(source, object);
        return (V) object;
    }

    public static <E, V> V beanConvert(E source, V destination) {
        BeanUtils.copyProperties(source, destination);
        return destination;
    }


    public static <E, V> List<V> listConvert(List<E> sources, Class<V> clazz) {
        List<V> targets = Lists.newArrayList();
        if (CollectionUtils.isEmpty(sources)) {
            return targets;
        }
        sources.stream().forEach(e -> targets.add(beanConvert(e, clazz)));
        return targets;
    }

}
